import 'package:flutter/material.dart';

class ListOptimised extends StatefulWidget {
  @override
  _ListOptimisedState createState() => _ListOptimisedState();
}

class _ListOptimisedState extends State<ListOptimised>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  ScrollController _scController = ScrollController();

  ///加载图片的标识
  bool isLoadingImage = true;

  bool showToTopBtn = false; //是否显示“返回到顶部”按钮

  ///网络图片地址
  String netImageUrl =
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201403%2F02%2F092241w9f4vaz8peovfe91.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617171292&t=b841f99b45f0beae202712d143ff6101";
  String netImageUrl1 =
      'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2Fattachments2%2Fday_100430%2F10043015437962673bf6152eff.jpg&refer=http%3A%2F%2Fattachments.gfan.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617171292&t=91015104cd9d4a4e2a23caf5d2d373ae';
  String netImageUrl2 =
      'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201310%2F24%2F110304ivraaalj3v33reao.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617171292&t=ce66276bc01447b6bc04eff42cee4c7b';
  String netImageUrl3 =
      'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2Fattachments2%2F201303%2F22%2F105956sdsnnsqjv4ts8ng4.jpg&refer=http%3A%2F%2Fattachments.gfan.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617171292&t=2c31d7800eb45594d95cc9541ec662ed';

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    //监听滚动事件，打印滚动位置
    _scController.addListener(() {
      print(_scController.offset); //打印滚动位置
      if (_scController.offset < 1000 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_scController.offset >= 1000 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  @override
  void didChangeDependencies() {
    print(MediaQuery.of(context).size.height);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    super.dispose();
    _scController.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text("详情"),
      ),

      ///列表
      body: NotificationListener(
        ///子Widget中的滚动组件滑动时就会分发滚动通知
        child: Scrollbar(child: buildListView()),

        ///每当有滑动通知时就会回调此方法
        onNotification: notificationFunction,
      ),
      floatingActionButton: !showToTopBtn
          ? null
          : FloatingActionButton(
              child: Icon(Icons.arrow_upward),
              onPressed: () {
                //返回到顶部时执行动画
                _scController.animateTo(.0,
                    duration: Duration(milliseconds: 200), curve: Curves.ease);
              }),
    );
  }

  bool notificationFunction(Notification notification) {
    ///通知类型
    switch (notification.runtimeType) {
      case ScrollStartNotification:
        print("开始滚动");

        ///在这里更新标识 刷新页面 不加载图片
        isLoadingImage = false;
        break;
      case ScrollUpdateNotification:
        print("正在滚动");
        break;
      case ScrollEndNotification:
        print("滚动停止");

        ///在这里更新标识 刷新页面 加载图片
        setState(() {
          isLoadingImage = true;
        });
        break;
      case OverscrollNotification:
        print("滚动到边界");
        break;
    }
    return true;
  }

  ListView buildListView() {
    return ListView.builder(
      controller: _scController,
      itemCount: 10000, //子条目个数
      itemExtent: 90.0, //列表项高度固定时，显式指定高度是一个好习惯(性能消耗小)
      ///构建每个条目
      itemBuilder: (BuildContext context, int index) {
        if (isLoadingImage) {
          ///这时将子条目单独封装在了一个StatefulWidget中
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Image.network(
                netImageUrl,
                width: 80,
                height: 80,
                fit: BoxFit.fitHeight,
              ),
              Image.network(
                netImageUrl1,
                width: 80,
                height: 80,
                fit: BoxFit.fitHeight,
              ),
              Image.network(
                netImageUrl2,
                width: 80,
                height: 80,
                fit: BoxFit.fitHeight,
              ),
              Image.network(
                netImageUrl3,
                width: 80,
                height: 80,
                fit: BoxFit.fitHeight,
              ),
            ],
          );
        } else {
          return Container(
            height: 100,
            width: 100,
            child: Center(child: Text("加载中...")),
          ); //占位
        }
      },

      ///构建每个子Item之间的间隔Widget
      // separatorBuilder: (BuildContext context, int index) {
      //   return Divider();
      // },
    );
  }
}
